<template>
  <edit-dialog :centerDialogVisible="visible" tilte="地图选择施工区域" width="80%" @Cancel="handleCancel" @Submit="handleConfirm"
               :default-button="pageType === ProjectFormType.ADD || pageType === ProjectFormType.EDIT">
    <template #content>
      <div class="add-map-area" v-loading="mapLoading">
        <map-control @mapLoad="mapLoadEvent"></map-control>
        <div class="operate-area">
          <div class="title" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
              <span>施工区域</span>
              <img src="@/assets/images/area-rectangle.png" style="margin: 0 10px;width: 15px;height: 15px;" @click="changeDrawType('polygon')" :style="{transform: `scale(${areaType==='polygon'?1.5:1})`}"/>
              <img src="@/assets/images/area-point.png" style="width: 15px;height: 15px;" @click="changeDrawType('point')" :style="{transform: `scale(${areaType==='point'?1.5:1})`}"/>
            </div>
            <div style="display: flex;" v-if="pageType === ProjectFormType.ADD || pageType === ProjectFormType.EDIT">
              <el-icon @click="clearMap">
                <Delete/>
              </el-icon>
              <el-icon @click="add" style="margin-left: 10px;">
                <Plus/>
              </el-icon>
            </div>
          </div>

          <el-radio-group v-model="form.isAll" @change="radioChange" :disabled="pageType === ProjectFormType.DETAIL || pageType === ProjectFormType.REVIEW">
            <div>
              <el-radio :label="0">选择本次作业的施工区域</el-radio>
              <el-input :disabled="form.isAll || pageType === ProjectFormType.DETAIL || pageType === ProjectFormType.REVIEW" v-model="form.areaName"
                        @focus="() => form.isAll = 0"/>
            </div>
            <el-radio :label="1">全场</el-radio>
          </el-radio-group>

          <!--          <span class="label">选中区域</span>-->
          <!--          <el-input v-model="form.area" :disabled="true"/>-->

          <span class="label">施工内容</span>
          <el-input v-model="form.constructionContent" type="textarea" rows="5" show-word-limit :maxlength="100"
                    :disabled="pageType === ProjectFormType.DETAIL || pageType === ProjectFormType.REVIEW"/>

          <span class="label">特种作业内容</span>
          <el-tree-select ref="selectJobRef" v-model="form.specialJobType" multiple collapse-tags :data="options.projectWorkTypeOptions" node-key="value"
                          placeholder="请选择" v-if="pageType === ProjectFormType.ADD || pageType === ProjectFormType.EDIT"
                          show-checkbox check-strictly :props="treeProps" class="tree-select" @change="specialJobChange"/>
          <el-input disabled v-model="form.specialJobContent" type="textarea" rows="3" style="margin-top: 10px;" :maxlength="200"/>
        </div>

        <div class="tools">
          <el-button size="small" type="primary" @click="scaleBar">
            <img src="@/assets/images/scalebar.png" style="width: 15px;"/>
          </el-button>
          <el-button icon="ZoomIn" size="small" type="primary" @click="zoomIn"></el-button>
          <el-button icon="ZoomOut" size="small" type="primary" @click="zoomOut"></el-button>
        </div>

        <el-radio-group size="mini" v-model="layerForm.layer" class="layer-group">
          <el-radio-button v-for="area in areaDetail" :label="area.buildName" @change="showFloor(area.floorDesc, area.buildName)" :key="area.buildName">
            {{ area.buildName }}
          </el-radio-button>
        </el-radio-group>

        <el-radio-group size="mini" v-model="layerForm.subLayer" class="subLayer">
          <el-radio-button v-for="area in subLayers" :label="area.buildName" @change="switchMap(area.name)" :key="area.name">
            {{ area.buildName }}
          </el-radio-button>
        </el-radio-group>

      </div>
    </template>
  </edit-dialog>
</template>

<script>
//地图控件
import MapControl from '@/components/map/index.vue'
import EditDialog from "@/components/editDialog/index.vue";
import {store} from '@/components/map/mapStore'
import {ref} from "vue";
import {areaDetail} from "@/config/config";
import {ProjectFormType} from "@/views/construction/project-daily/projectUtil";

export default {
  name: "AddMapArea",
  components: {MapControl, EditDialog},
  inject: ['options', 'pageType'],
  props: {
    location: {
      type: String,
    }
  },
  data() {
    return {
      mapLoading: true,
      visible: false,
      tool: undefined,
      row: undefined,
      areaType: 'polygon',
      form: {
        isAll: 0
      },
      treeProps: {
        label: 'label',
        disabled: (data, node) => {
          return data.children
        }
      },
      layerForm: {
        layer: areaDetail[0].buildName,
        subLayer: undefined
      },
      areaDetail: areaDetail,
      subLayers: [],
      ProjectFormType
    }
  },
  methods: {
    open({row, resolve}) {
      let form = {}
      if (row) {
        form = row
        this.row = row
      } else {
        this.row = undefined
        form.isAll = 0
      }
      this.resolve = resolve
      this.visible = true
      this.form = form

      if (this.location) {
        this.layerForm.layer = this.location
        let find = this.areaDetail.find(item => item.buildName === this.location)
        this.showFloor(find.floorDesc, find.buildName)
      }
    },
    changeDrawType(type) {
      this.areaType=type
      this.clearMap()
    },
    radioChange(val) {
      if (val) {
        this.form.areaName = '全场'
        this.disabledMap()
      } else {
        this.form.areaName = ''
        this.clearMap()
        this.form.areaName = undefined
      }
      this.form.area = undefined
    },
    specialJobChange() {
      let checkedNodes = this.$refs.selectJobRef.getCheckedNodes()
      this.form.specialJobContent = checkedNodes.map(item => item.label).join(',')
    },
    handleConfirm() {
      if (!this.validForm()) return
      this.resolve(this.row ? undefined : this.form)
      this.handleCancel()
    },
    validForm() {
      if (!this.form.isAll && !this.form.areaName) {
        this.$message.warning('请输入区域名称')
        return
      }
      if (!this.form.isAll && !this.form.area) {
        this.$message.warning('请选择区域')
        return
      }
      if (!this.form.constructionContent) {
        this.$message.warning('请输入施工内容')
        return
      }
      if (!this.form.specialJobType) {
        this.$message.warning('请选择特种作业种类')
        return
      }
      if (!this.form.specialJobContent) {
        this.$message.warning('请输入特种作业内容')
        return
      }
      return true
    },
    handleCancel() {
      this.visible = false
    },
    add() {
      if (!this.validForm()) return
      this.resolve(this.row ? undefined : this.form)
      this.form = {}
      this.row = undefined
      this.clearMap()
    },
    clearMap() {
      this.form.area = undefined
      this.draw()
    },
    disabledMap() {
      this.form.area = undefined
      store.BNMap.removeGraphicsLayer('demo')
    },
    showFloor(subLayers) {
      this.subLayers = subLayers
      this.layerForm.subLayer = undefined
    },
    switchMap(name) {
      store.BNMap.switchDCJ(name, () => {
        // 一般为调用setCenter和setLevel方法
      })
    },
    mapLoadEvent() {
      this.mapLoading = false
      if (this.row) {
        let arr = this.row.area
        this.editInit(JSON.parse(arr))
      } else {
        this.draw()
      }
    },
    draw(type) {
      // "point"：点、"line"：线、"freeline"：自由线、 "polygon"：面
      // "circle"：圆、"curve"：弧线、"freehandarrow"：箭头、"multihead"：多箭头、"beziercurve"：bezier线、"bezierpolygon"：bezier面
      let tool = this.drawMap()
      tool.activate(this.areaType);
    },
    drawMap() {
      store.BNMap?.removeGraphicsLayer('demo')
      // 向地图添加临时图层
      const clickLayer = store.BNMap.creatGraphicsLayer({id: 'demo'})
      clickLayer.removeAll()
      store.BNMap.addGraphicsLayer(clickLayer)
      return store.BNMap.createPlot(
        {
          gl: clickLayer,//指定操作图层
          fillSymbol: {//设置绘制面样式
            color: [227, 139, 79, 0.8],
            outline: {
              color: [255, 255, 255],
              width: 1
            }
          },
          lineSymbol: {
            color: [226, 119, 40],
            width: 2
          },
          pointSymbol: {
            color: [226, 119, 40],
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {//参数二：绑定事件
          complete: (e) => {
            // 传接口只需要传递e.graphic.geometry.rings
            // 为了显示处理为字符串,字符串无需传给接口
            // let temp = ""
            if (e.graphic) {
              let arr = []
              if (this.areaType === 'polygon') {
                e.graphic.geometry.rings[0].forEach((r) => {
                  // temp += r[0] + "," + r[1] + ";"
                  // const arr = ref({
                  //   latitude: "", longitude: ""
                  // })
                  // arr.value.latitude = r[0]
                  // arr.value.longitude = r[1]
                  arr.push([r[0], r[1]])
                })
              } else {
                arr.push([e.graphic.geometry.x, e.graphic.geometry.y])
              }
              this.form.area = JSON.stringify(arr)
            }
          }
        },
      );
    },
    zoomOut() {
      store.BNMap.zoomOut()
    },
    zoomIn() {
      store.BNMap.zoomIn()
    },
    editInit(arr) {
      const BNMap = store.BNMap
      const BNGeometry = store.BNGeometry
      const BNSymbol = store.BNSymbol
      if (arr.length === 1) {
        this.areaType = 'point'
        // 获取点
        const Point=BNGeometry.createPoint(arr[0][0], arr[0][1], BNMap.spatialReference);
        // 设置点样式
        const pointSymbols=BNSymbol.pointSymbol("red","18");
        const graphics=BNMap.graphic(Point,pointSymbols);

        const graphicsLayer = BNMap.creatGraphicsLayer({id: "demo"});
        BNMap.addGraphicsLayer(graphicsLayer);
        graphicsLayer.add(graphics);
      } else {
        this.areaType = 'polygon'
        //面 使用坐标新增
        const polygonJson = {
          "rings": [arr],
          "spatialReference": BNMap.spatialReference
        };
        const polygon = BNGeometry.createPolygon(polygonJson);
        // 线
        const polygonSymbol = BNSymbol.polygonSymbol(
          // 面的样式  实线
          "solid",
          // 边框样式
          {
            color: [255, 255, 255],
            width: 1
          },
          // 面的填充颜色
          [227, 139, 79, 0.8]
        );
        const graphics = BNMap.graphic(polygon, polygonSymbol);
        const graphicsLayer = BNMap.creatGraphicsLayer({id: "demo"});
        BNMap.addGraphicsLayer(graphicsLayer);
        graphicsLayer.add(graphics);
        BNMap.setCenter(BNGeometry.createPoint(arr[0][0][0], arr[0][0][1], BNMap.spatialReference));
      }
    },
    scaleBar() {
      if (this.scaleBarShow) {
        this.scaleBarShow.destroy()
        this.scaleBarShow = undefined
      } else {
        let res = store.BNMap.creatScalebar()
        this.scaleBarShow = res
      }
    }
  }
}
</script>

<style lang="less" scoped>
.add-map-area {
  height: 650px;
  background: rgba(116, 215, 234, 0.62);
  position: relative;

  .operate-area {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 15px;
    left: 15px;
    bottom: 60px;
    width: 270px;
    background: white;
    border: 4px;
    border-radius: 8px;
    padding: 12px;

    .title {
      position: relative;
      margin-bottom: 10px;
      padding-left: 13px;
      font-size: 16px;
      font-weight: 500;

      &:before {
        position: absolute;
        content: '';
        left: 0;
        top: 1px;
        height: 20px;
        border-radius: 2px;
        width: 6px;
        background: #2F7DF1;
      }
    }

    .label {
      margin-top: 20px;
      margin-bottom: 10px;
    }
  }

  .layer-group {
    position: absolute;
    right: 20px;
    bottom: 20px;
  }

  .tools {
    position: absolute;
    display: flex;
    flex-direction: column;
    width: 35px;
    top: 80px;
    right: 20px;
    border: 0;

    .el-button {
      margin-left: 0;
      margin-top: 5px;
    }
  }

  .subLayer {
    position: absolute;
    width: 35px;
    bottom: 80px;
    right: 20px;
    border: 0;
  }

  .subLayer /deep/ .el-radio-button .el-radio-button__inner {
    width: 35px;
    border: 1px #FFF solid;
    padding: 10px;
  }

  .subLayer /deep/ .el-radio-button:first-child .el-radio-button__inner {
    border-radius: 6px 6px 0 0;
  }

  .subLayer /deep/ .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 0 0 6px 6px;
  }
}

::v-deep .tree-select :not(.is-leaf) + .is-disabled {
  display: none !important;
}
</style>
